<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { NetoKit } from '@/typings/neto';
import { SyssensitivewordApi } from '@/api-services/apis/syssensitiveword-api';
import { ApiSysUserLoginRuleInput } from '@/api-services';
import { SysuserloginruleApi } from '@/api-services/apis/sysuserloginrule-api';

defineOptions({
  name: 'SysUserLoginRuleOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  editId?: number | undefined;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t('page.manage.userLoginRule.addLoginRule'),
    edit: $t('page.manage.userLoginRule.addLoginRule')
  };
  return titles[props.operateType];
});


type Model = NetoKit.IsNonNullable<ApiSysUserLoginRuleInput>;
const model = ref(createDefaultModel());
function createDefaultModel(): Model {
  return {
    id: 0,
    name: '',
    loginRuleType: 1,
    maxFailCount: 0,
    lockMinutes: 0,
    isEnable: true,
    remark: ''
  }
}



async function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.editId) {
    const [err, res] = await feature(getAPI(SysuserloginruleApi).get(props.editId));
    queryDone(err, () => {
      const data = res?.data.data;
      if (data) {
        Object.assign(model.value, data);
      }
    })
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();






  if (props.operateType === 'add') {
    const [err, res] = await feature(getAPI(SysuserloginruleApi).insert(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.addSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  } else {
    const [err, res] = await feature(getAPI(SysuserloginruleApi).update(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  }

}
type RuleKey = Extract<keyof Model, 'word'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" modal-height="" width="800px">
    <ElForm ref="formRef" label-width="auto" :model="model" :rules="rules">
      <ElRow :gutter="16" wrap>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.userLoginRule.name')" name="name">
            <ElInput v-model="model.name" style="width: 100%" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.common.loginRuleType')" name="loginRuleType">
            <ElSelect v-model="model.loginRuleType">
              <ElOption :value="1" :label="$t('page.manage.common.loginRuleTypeEnum.pwd')" />
              <ElOption :value="2" label="Ip" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.userLoginRule.maxFailCount')" name="maxFailCount">
            <ElInputNumber v-model="model.maxFailCount" style="width: 100%" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.userLoginRule.lockMinutes')" name="lockMinutes">
            <ElInputNumber v-model="model.lockMinutes" style="width: 100%" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.common.isEnable')" name="isEnable">
            <ElSwitch v-model:model-value="model.isEnable" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.manage.common.remark')" name="remark">
            <ElInput type="textarea" v-model="model.remark" :auto-size="{ minRows: 2, maxRows: 5 }" />
          </ElFormItem>
        </ElCol>
      </ElRow>

    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
